package com.jxnu.duewang.zmly.fragment;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.jxnu.duewang.zmly.R;
import com.jxnu.duewang.zmly.databinding.FragmentRecommendBinding;
import com.jxnu.duewang.zmly.zouZhen.activity.MusicActivity;
import com.jxnu.duewang.zmly.zouZhen.adapter.DiscoverColumnImageAdapter;
import com.jxnu.duewang.zmly.zouZhen.adapter.DiscoverFocusImageAdapter;
import com.jxnu.duewang.zmly.zouZhen.adapter.DiscoverSpecialColumnRecycleViewAdapter;
import com.jxnu.duewang.zmly.zouZhen.adapter.ListViewAdapter;
import com.jxnu.duewang.zmly.zouZhen.agency.DiscoveryRxJavaService;
import com.jxnu.duewang.zmly.zouZhen.model.DataBindingDiscoverEditorRecommend;
import com.jxnu.duewang.zmly.zouZhen.model.DatabindingDiscoverColumn;
import com.jxnu.duewang.zmly.zouZhen.model.DatabindingDiscoverRecommendFocusData;
import com.jxnu.duewang.zmly.zouZhen.model.DatabindingDiscoverSpecialColumn;
import com.jxnu.duewang.zmly.zouZhen.model.DiscoverFirstData;
import com.jxnu.duewang.zmly.zouZhen.model.DiscoverFirstDataDiscoveryColumnsList;
import com.jxnu.duewang.zmly.zouZhen.model.DiscoverFirstDataEditorRecommendAlbumsList;
import com.jxnu.duewang.zmly.zouZhen.model.DiscoverFirstDataFocusImageList;
import com.jxnu.duewang.zmly.zouZhen.model.DiscoverFirstDataSpecialColumnList;
import com.jxnu.duewang.zmly.zouZhen.widget.DiscoveryColumnsViewPager;
import com.jxnu.duewang.zmly.zouZhen.widget.DiscoveryEditorListView;
import com.jxnu.duewang.zmly.zouZhen.widget.DiscoverySpecialRecycleView;
import com.jxnu.duewang.zmly.zouZhen.widget.RxBus;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecommendFragment extends BaseFragment implements ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private TextView mTvText;
    private LinearLayout mLinearDot;
    private ArrayList<DatabindingDiscoverRecommendFocusData> mAdlist;
    private Handler h;
    private DiscoverFocusImageAdapter mFocusImageAdapter;
    private Observable<DiscoverFirstData> mDiscoverFirstData;
    private DiscoveryColumnsViewPager mColumnsViewPager;
    private List<DatabindingDiscoverColumn> mColumnList;
    private DiscoverColumnImageAdapter mDiscoverColumnImageAdapter;
    private LinearLayout mLinearColumnsDots;
    private DiscoveryEditorListView mListView;
    private ListViewAdapter mListViewAdapter;
    private List<DataBindingDiscoverEditorRecommend> mDataBindingDiscoverEditorRecommends;
    private ScrollView mScrollView;
    private List<DatabindingDiscoverSpecialColumn> mDatabindingDiscoverSpecialColumns;
    private DiscoverySpecialRecycleView mRecyclerView;
    private DiscoverSpecialColumnRecycleViewAdapter mSpecialRecycleViewAdapter;
    private Subscription rxBus;

    public RecommendFragment() {
        if(h==null){
            h=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
                    h.sendEmptyMessageDelayed(0,6000);
                }
            };
        }
    }


    @Override
    public String getFragmnetTitle() {
        return "推荐";
    }

    //use RxBus instead of EventBus
//    @Override
//    public void onStart() {
//        super.onStart();
//        EventBus.getDefault().register(this);
//    }
//
//    @Override
//    public void onStop() {
//        super.onStop();
//        EventBus.getDefault().unregister(this);
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(View view){
//        Toast.makeText(view.getContext(), "you click this", Toast.LENGTH_SHORT).show();
//    }


    @Override
    public void onStart() {
        super.onStart();
        rxBus = RxBus.getDefault().toObservable(View.class)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<View>() {
                    @Override
                    public void call(View view) {
                        startActivity(new Intent(getContext(),MusicActivity.class));
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Toast.makeText(getContext(), "recycleView's click event error", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onStop() {
        super.onStop();
        //if rxbus subscribed
        if (!rxBus.isUnsubscribed()) {
            rxBus.unsubscribe();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentRecommendBinding inflate = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_recommend, container, false);
        initView(inflate);
        View ret = inflate.getRoot();
        ininListener();
        initData();
        fragmentContentFromNetWork();

        return ret;
    }

    public void initView(FragmentRecommendBinding inflate){

        mViewPager = inflate.headAdv;
        mTvText = inflate.glideHead;
        mLinearDot = inflate.dot;
        mColumnsViewPager = inflate.discoverColumns;
        mLinearColumnsDots = inflate.discoverColumnsDot;
        mListView = inflate.discoverListView;
        mScrollView = inflate.discoverScroll;
        mRecyclerView = inflate.discoverRecycleview;

//        mViewPager = ((ViewPager) view.findViewById(head_adv));
//        mTvText = ((TextView) view.findViewById(glideHead));
//        mLinearDot = ((LinearLayout) view.findViewById(R.id.dot));
//        mColumnsViewPager = ((DiscoveryColumnsViewPager) view.findViewById(R.id.discover_columns));
//        mLinearColumnsDots = ((LinearLayout) view.findViewById(R.id.discover_columns_dot));
//        mListView = ((DiscoveryEditorListView) view.findViewById(R.id.discover_list_view));
//        mScrollView = ((ScrollView) view.findViewById(R.id.discover_scroll));
//        mRecyclerView = ((DiscoverySpecialRecycleView) view.findViewById(R.id.discover_recycleview));
    }

    public void ininListener(){
        mViewPager.addOnPageChangeListener(this);
        mColumnsViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            private EdgeEffectCompat leftEdge;
//            private EdgeEffectCompat rightEdge;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                try {
//                    Field leftEdgeField = mColumnsViewPager.getClass().getDeclaredField("mLeftEdge");
//                    Field rightEdgeField = mColumnsViewPager.getClass().getDeclaredField("mRightEdge");
//                    if(leftEdgeField != null && rightEdgeField != null){
//                        leftEdgeField.setAccessible(true);
//                        rightEdgeField.setAccessible(true);
//                        leftEdge = (EdgeEffectCompat) leftEdgeField.get(mColumnsViewPager);
//                        rightEdge = (EdgeEffectCompat) rightEdgeField.get(mColumnsViewPager);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                if(leftEdge != null && rightEdge != null) {
//                    leftEdge.finish();
//                    rightEdge.finish();
//                    leftEdge.setSize(0, 0);
//                    rightEdge.setSize(0, 0);
//                }
            }

            @Override
            public void onPageSelected(int position) {
                updateColumnDots();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void initData(){
        mAdlist = new ArrayList<>();
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        mAdlist.add(new DatabindingDiscoverRecommendFocusData(null," "));
        initDots();

        mViewPager.setOffscreenPageLimit(mAdlist.size());
        mFocusImageAdapter = new DiscoverFocusImageAdapter(getContext(), mAdlist);
        mViewPager.setAdapter(mFocusImageAdapter);
        int centerValue = Integer.MAX_VALUE / 2;
        int value = centerValue % mAdlist.size();
        mViewPager.setCurrentItem(centerValue-value);

        updateTextAndDot();
        h.sendEmptyMessageDelayed(0, 6000);

        mColumnList=new ArrayList<>();
        List<String> texts=new ArrayList<>(4);
        texts.add("喜马拉雅");
        texts.add("喜马拉雅");
        texts.add("喜马拉雅");
        texts.add("喜马拉雅");
        List<String> urls=new ArrayList<>(4);
        urls.add(null);
        urls.add(null);
        urls.add(null);
        urls.add(null);
        mColumnList.add(new DatabindingDiscoverColumn(texts,urls));
        mColumnList.add(new DatabindingDiscoverColumn(texts,urls));
        initColumnsDots();
        updateColumnDots();
        mColumnsViewPager.setOffscreenPageLimit(mColumnList.size());
        mDiscoverColumnImageAdapter = new DiscoverColumnImageAdapter(getContext(),mColumnList);
        mColumnsViewPager.setAdapter(mDiscoverColumnImageAdapter);
        mColumnsViewPager.setCurrentItem(0);


        mDataBindingDiscoverEditorRecommends=new ArrayList<>();
        List<String> titles=new ArrayList<>();
        List<String> cla=new ArrayList<>();
        titles.add("duewang");
        titles.add("duewang");
        titles.add("duewang");
        cla.add("喜马拉雅");
        cla.add("喜马拉雅");
        cla.add("喜马拉雅");
        List<String> editorUrls=new ArrayList<>();
        editorUrls.add(null);
        editorUrls.add(null);
        editorUrls.add(null);
//        ArrayList<String> strings = new ArrayList<>(titles);
//        ArrayList<String> strings1 = new ArrayList<>(cla);
//        ArrayList<String> strings2 = new ArrayList<>(editorUrls);
        DataBindingDiscoverEditorRecommend editorRecommend =  new DataBindingDiscoverEditorRecommend("小编推荐", titles, cla, editorUrls);
//        DataBindingDiscoverEditorRecommend editorRecommend1 =  new DataBindingDiscoverEditorRecommend("小编推荐", strings, strings1, strings2);
        mDataBindingDiscoverEditorRecommends.add(editorRecommend);
//        mDataBindingDiscoverEditorRecommends.add(editorRecommend1);
        mListViewAdapter = new ListViewAdapter(getContext(),mDataBindingDiscoverEditorRecommends);
        mListView.setAdapter(mListViewAdapter);
//        CalculateListViewHeight.setListViewHeightBasedOnchildren(mListView);
        mScrollView.smoothScrollTo(0,0);

        mDatabindingDiscoverSpecialColumns=new ArrayList<>();
        DatabindingDiscoverSpecialColumn databindingDiscoverSpecialColumn = new DatabindingDiscoverSpecialColumn("精品听单", "喜马拉雅", "来喜马拉雅听故事", "我的声音", null);
        mDatabindingDiscoverSpecialColumns.add(databindingDiscoverSpecialColumn);
        LinearLayoutManager layoutManager  = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
//        DiscoverSpecialRecycleViewLayoutManager layoutManager = new DiscoverSpecialRecycleViewLayoutManager(getContext());
//        layoutManager.setOrientation(OrientationHelper.VERTICAL);
//        layoutManager.setSmoothScrollbarEnabled(true);
//        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setLayoutManager(layoutManager);
        mSpecialRecycleViewAdapter = new DiscoverSpecialColumnRecycleViewAdapter(getContext(), mDatabindingDiscoverSpecialColumns);
        mRecyclerView.setAdapter(mSpecialRecycleViewAdapter);
//        mRecyclerView.addItemDecoration(new MyItemDecoration());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    private void updateTextAndDot(){
        int currentPage = mViewPager.getCurrentItem() % mAdlist.size();
        mTvText.setText(mAdlist.get(currentPage).getText());

        for(int i=0;i<mLinearDot.getChildCount();i++){
            mLinearDot.getChildAt(i).setEnabled(i==currentPage);
        }

    }

    public void initDots(){
        for (int i = 0; i < mAdlist.size(); i++) {
            View view = new View(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
            if(i!=0){
                params.leftMargin=5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.seletor_dot);
            mLinearDot.addView(view);
        }
    }

    public void initColumnsDots(){
        for (int i = 0; i < mColumnList.size(); i++) {
            View view = new View(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
            if(i!=0){
                params.leftMargin=5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.column_seletor_dot);
            mLinearColumnsDots.addView(view);
        }
    }

    public void updateColumnDots(){
        int currentPage = mColumnsViewPager.getCurrentItem();

        for(int i=0;i<mLinearColumnsDots.getChildCount();i++){
            mLinearColumnsDots.getChildAt(i).setEnabled(i==currentPage);
        }
    }

    private void fragmentContentFromNetWork(){
        DiscoveryRxJavaService discoveryRxJavaService = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .build()
                .create(DiscoveryRxJavaService.class);
        mDiscoverFirstData = discoveryRxJavaService.getDiscoverFirstData();
        mDiscoverFirstData
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DiscoverFirstData>() {

                    @Override
                    public void onStart() {
                        ConnectivityManager connectivityManager = (ConnectivityManager) getContext() .getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                        if(!activeNetInfo.isConnected() && !mobNetInfo.isConnected()) {
                            onCompleted();
                        }
                        super.onStart();
                    }

                    @Override
                    public void onCompleted() {
                        mDiscoverFirstData.unsubscribeOn(Schedulers.io());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(DiscoverFirstData discoverFirstData) {
                        h.removeMessages(0);
                        List<DiscoverFirstDataFocusImageList> discoverFirstDataFocusImageLists = discoverFirstData.getDiscoverFirstDataFocusImage().getDiscoverFirstDataFocusImageLists();
                        int size = discoverFirstDataFocusImageLists.size();
                        if (size>0){
                            mAdlist.clear();
                            for (int i = 0; i < size; i++) {
                                DatabindingDiscoverRecommendFocusData focusData = new DatabindingDiscoverRecommendFocusData(discoverFirstDataFocusImageLists.get(i).getPicUrl(), discoverFirstDataFocusImageLists.get(i).getShortTitle());
                                mAdlist.add(focusData);
                            }
                            mLinearDot.removeAllViews();
                            initDots();
                            mViewPager.setOffscreenPageLimit(mAdlist.size());
                            mFocusImageAdapter.notifyDataSetChanged();
                        }
                        int centerValue = Integer.MAX_VALUE / 2;
                        int value = centerValue % mAdlist.size();
                        mViewPager.setCurrentItem(centerValue-value);

                        updateTextAndDot();
                        h.sendEmptyMessageDelayed(0, 6000);

                        List<DiscoverFirstDataDiscoveryColumnsList> discoverFirstDataDiscoveryColumnsLists = discoverFirstData.getDiscoverFirstDataDiscoveryColumns().getDiscoverFirstDataDiscoveryColumnsLists();
                        int len = discoverFirstDataDiscoveryColumnsLists.size();
                        mColumnList.clear();
                        for (int i = 0; i < len; i++) {
                            List<String> texts=new ArrayList<>(4);
                            List<String> urls=new ArrayList<>(4);
                            for (int j = 0; j < 4&&i < len; j++,i++) {
                                texts.add(discoverFirstDataDiscoveryColumnsLists.get(i).getTitle());
                                urls.add(discoverFirstDataDiscoveryColumnsLists.get(i).getCoverPath());
                            }
                            if(i < len){
                                i--;
                            }
                            DatabindingDiscoverColumn discoverColumn = new DatabindingDiscoverColumn(texts, urls);
                            mColumnList.add(discoverColumn);
                        }
                        mLinearColumnsDots.removeAllViews();
                        initColumnsDots();
                        mColumnsViewPager.setOffscreenPageLimit(mColumnList.size());
                        mDiscoverColumnImageAdapter.notifyDataSetChanged();
                        mColumnsViewPager.setCurrentItem(0);
                        updateColumnDots();

                        mDataBindingDiscoverEditorRecommends.clear();
                        String title = discoverFirstData.getDiscoverFirstDataEditorRecommendAlbums().getTitle();
                        List<DiscoverFirstDataEditorRecommendAlbumsList> discoverFirstDataEditorRecommendAlbumsLists = discoverFirstData.getDiscoverFirstDataEditorRecommendAlbums().getDiscoverFirstDataEditorRecommendAlbumsLists();
                        List<String> titles=new ArrayList<>();
                        List<String> cla=new ArrayList<>();
                        List<String> editorUrls=new ArrayList<>();
                        len = discoverFirstDataEditorRecommendAlbumsLists.size();
                        for (int i = 0; i < len; i++) {
                            for (int j = 0; j < 3 && i < len; j++,i++) {
                                titles.add(discoverFirstDataEditorRecommendAlbumsLists.get(i).getTitle());
                                cla.add(discoverFirstDataEditorRecommendAlbumsLists.get(i).getTrackTitle());
                                editorUrls.add(discoverFirstDataEditorRecommendAlbumsLists.get(i).getAlbumCoverUrl());
                            }
                            DataBindingDiscoverEditorRecommend dataBindingDiscoverEditorRecommend = new DataBindingDiscoverEditorRecommend(title, titles, cla, editorUrls);
                            mDataBindingDiscoverEditorRecommends.add(dataBindingDiscoverEditorRecommend);
                            if(i<len){
                                i--;
                            }
                        }
                        mListViewAdapter.notifyDataSetChanged();

                        mDatabindingDiscoverSpecialColumns.clear();
                        title = discoverFirstData.getDiscoverFirstDataSpecialColumn().getTitle();
                        List<DiscoverFirstDataSpecialColumnList> discoverFirstDataSpecialColumnLists = discoverFirstData.getDiscoverFirstDataSpecialColumn().getDiscoverFirstDataSpecialColumnLists();
                        for (int i = 0; i < discoverFirstDataSpecialColumnLists.size(); i++) {
                            DatabindingDiscoverSpecialColumn databindingDiscoverSpecialColumn = new DatabindingDiscoverSpecialColumn(discoverFirstDataSpecialColumnLists.get(i).getTitle(), title, discoverFirstDataSpecialColumnLists.get(i).getSubtitle(), discoverFirstDataSpecialColumnLists.get(i).getFootnote(), discoverFirstDataSpecialColumnLists.get(i).getCoverPath());
                            mDatabindingDiscoverSpecialColumns.add(databindingDiscoverSpecialColumn);
                        }
                        mSpecialRecycleViewAdapter.notifyDataSetChanged();

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewPager.removeOnPageChangeListener(this);
        h.removeMessages(0);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        h.removeMessages(0);
        updateTextAndDot();
        h.sendEmptyMessageDelayed(0,6000);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

}
